

/*
 * @Author: zhengguiyong zhengguiyong@sailvan.com
 * @Date: 2023-09-22 15:32:15
 * @LastEditors: zhengguiyong zhengguiyong@sailvan.com
 * @LastEditTime: 2023-10-30 10:21:55
 * @FilePath: /tbox_meige_CHG/tbox_meige2/src/sys/activate.c
 * @Description: 激活状态管理文件
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#include "global.h"
#define  LOG_TAG TAG_TBOX
#include "easylog/elog.h"

#include "include/swei_config.h"
#include "include/swei_downlink.h"
#include "include/swei_cmd.h"
#include "include/swei_login.h"
#include "comm/co_heartbeat.h"

#include "misc/misc_system.h"
#include "misc/misc_api.h"

/**
 * @brief 激活设备
 * @param  uuid             My Param doc
 * @param  activated        My Param doc
 */
void swei_activate_device_proc(uint32_t uuid, uint8_t activated)
{
    uint32_t    id  = 0;
    uint8_t     act = 0;

    swei_config_set_userid(uuid);
    id = swei_config_get_userid();                          /* 回读 */

    swei_config_set_activated(activated);                   /* 设置设备处于激活状态 */
    act = (ACTIVE == misc_get_active_state() ? true : false);

    /* 非激活模式需要请求关闭仪表 */
    if (!act) {
        tbox_system_poweroff(1000);
    }

    log_i("swei_%s_device uuid[%#x]", false == act ? "unactivate" : "activate", id);
}

/**
 * @description: 下行激活设备
 * @param {int} uuid
 * @param {unsigned char} *data
 * @return {*}
 * @Date: 2023-10-30 10:21:44
 * @modification:
 */
static DLCMD_RET_TYPE_ENUM swei_activate_device(DOWN_LINK_CMD_ENUM cmd_id, uint16_t cmd_opcode, const unsigned char *p_data, uint32_t data_len)
{
    if (data_len != 4) {
        log_e("data len[%d] err!", data_len);
        return DLCMD_RET_ERROR;
    }
    int uuid = p_data[0] << 24 | p_data[1] << 16 | p_data[2] << 8 | p_data[3];

    swei_activate_device_proc(uuid, true);

    return DLCMD_RET_FINISH;
}

static DLCMD_RET_TYPE_ENUM swei_unactivate_device(DOWN_LINK_CMD_ENUM cmd_id, uint16_t cmd_opcode, const unsigned char *p_data, uint32_t data_len)
{
    swei_activate_device_proc(0, false);

    return DLCMD_RET_FINISH;
}

/**
 * @description: 激活功能初始化
 * @return {*}
 * @Date: 2023-09-22 15:37:30
 * @modification:
 */
void swei_activate_init(void)
{
    log_i("tbox init set device activate:[%d]", misc_get_active_state());
    // 注册下行指令处理函数
    swei_downlink_cmd_register(DOWN_LINK_CMD_ACTIVATE, swei_activate_device);
    swei_downlink_cmd_register(DOWN_LINK_CMD_UNACTIVATE, swei_unactivate_device);
    return;
}
